package dao.impl;

import dao.BaseDao;
import dao.BookDao;
import entity.Book;
import utils.DataBaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl extends BaseDao implements BookDao {
    public BookDaoImpl(Connection conn) {
        super(conn);
    }

    @Override
    public List<Book> findByPage(int pageIndex, int pageSize) throws SQLException {
        List<Book> list = new ArrayList<>();
        String sql = "select * from books limit ?,?";
        PreparedStatement stmt = this.conn.prepareStatement(sql);
        ResultSet rs = this.query(stmt, pageIndex, pageSize);
        while (rs.next()) {
            Book book = new Book();
            book.setId(rs.getInt("id"));
            book.setTitle(rs.getString("title"));
            list.add(book);
        }
        DataBaseUtil.closeAll(conn, stmt, rs);
        return list;
    }

    @Override
    public Integer getTotalCount() throws SQLException {
        int totalCount = 0;
        String sql = "select count(id) as totalCount from books";
        PreparedStatement stmt = this.conn.prepareStatement(sql);
        ResultSet rs = this.query(stmt);
        if (rs.next()) {
            totalCount = rs.getInt("totalCount");
        }
        DataBaseUtil.closeAll(conn, stmt, rs);
        return totalCount;
    }
}
